package com.greendragon.interceptor; 

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.greendragon.control.constant.GlobalConstants;
import com.greendragon.persistence.domain.User;
import com.greendragon.service.frontend.IUserFrontendService;
import com.greendragon.util.CookieUtil;
import com.greendragon.util.EncryptionUtil;
import com.greendragon.util.TokenUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/** 
 * 验证是否使用 "记住我" 登入
 * @author wulibin, exceptsky@gmail.com, 2011-9-11 下午12:14:26
 * 
 */
public class RemMeCheckInterceptor extends AbstractInterceptor{
	private static final long serialVersionUID = -5318934379200910473L;

	private IUserFrontendService userFrontendService;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		ActionContext actionContext = invocation.getInvocationContext();
		Map<String, Object> session = actionContext.getSession();
		if (session != null) {
			if (session.get(GlobalConstants.SESSION_LOGIN_USER) == null) {
				User user = checkCookieLogin();
				if (null != user) {
					session.put(GlobalConstants.SESSION_LOGIN_USER, user);
				}
			}
		}
		return invocation.invoke();
	}

	private User checkCookieLogin() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String token = CookieUtil.getCookie(request, GlobalConstants.COOKIE_REMEMBER_ME);
		if (StringUtils.isNotBlank(token)) {
			String tokens[] = token.split("-");
			if (tokens.length != 3) {
				return null;
			}
			String id = new String(EncryptionUtil.getFromBASE64(tokens[0]));
			if (true == TokenUtil.checkToken(id, token)) {
				User loginUser = userFrontendService.get(Long.valueOf(id));
				return loginUser;
			}
		}
		return null;
	}

	public void setUserFrontendService(IUserFrontendService userFrontendService) {
		this.userFrontendService = userFrontendService;
	}

}
 